<template>
  <el-upload
    :show-file-list="false"
    :on-success="handleImageSuccess"
    :before-upload="beforeUpload"
    :on-progress="onProgress"
    class="image-uploader"
    action="http://whg.fzsglqwhg.com/member/upload-image">
    <img v-if="image" :src="image" class="image">
    <i v-else class="el-icon-plus image-uploader-icon" />
    <el-progress v-if="!image && videoUploadPercent" :percentage="videoUploadPercent" class="percent" type="circle" />
  </el-upload>
</template>
<script>
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      videoUploadPercent: 0
    }
  },
  computed: {
    image() {
      return this.value
    }
  },
  methods: {
    emitInput(val) {
      this.$emit('input', val)
    },
    onProgress(event, file, fileList) {
      this.videoUploadPercent = parseInt(event.percent.toFixed(0), 10)
    },
    handleImageSuccess(res, file) {
      // 图片
      this.emitInput(res.resource.url)
    },
    beforeUpload(file) {
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isLt20M) {
        this.$message.error('上传头像图片大小不能超过 20MB!')
      }
      return isLt20M
    }
  }
}
</script>
<style lang="scss">
  .el-progress-circle {
    background: #fff;
  }
  .image-uploader {
    position: relative;
  }
  .image-uploader .percent {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  .image-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .image-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .image-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .image {
    max-width: 200px;
    display: block;
  }
</style>
